package com.chenwc.netty.tcp.coder;

import com.alibaba.fastjson.JSONObject;
import com.chenwc.netty.tcp.enums.MessageEnum;

/**
 * 数据解码转换的实例 Message类用于承载消息、转JsonString
 * @author chenwc
 * @date 2023/5/28 0:59
 */

public class Message {

    /**
     * 数据长度
     */
    private Integer len;

    /**
     * 接收的通讯数据body
     */
    private String body;

    /**
     * 消息类型
     */
    private MessageEnum msgType;

    public Message(Object object) {
        String str = object.toString();
        //log.info("receive: {}", str);
        JSONObject jsonObject = JSONObject.parseObject(str);
        msgType = MessageEnum.getStructureEnum(Integer.valueOf(jsonObject.getString("msg_type")));
        body = jsonObject.getString("body");
        len = str.length();
    }

    public Message(String body, MessageEnum msgType) {
        this.body = body;
        this.msgType = msgType;
        this.len = body.length();
    }

    public String toJsonString() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg_type", msgType.getType());
        jsonObject.put("body", body);
        return jsonObject.toJSONString();
    }

    public Integer getLen() {
        return len;
    }

    public void setLen(Integer len) {
        this.len = len;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public MessageEnum getMsgType() {
        return msgType;
    }

    public void setMsgType(MessageEnum msgType) {
        this.msgType = msgType;
    }
}
